package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Employee;

import dao.EmployeeDAO;


/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
    EmployeeDAO  emDao;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String mes = request.getParameter("mes");
		
		HttpSession session = request.getSession();
		if(null != mes && mes.equalsIgnoreCase("out")) {
			if (!session.isNew()) {
			    session.invalidate();
			}
		}
		
		response.sendRedirect("gui.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Employee user = new Employee();
		int id;
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		try {
			emDao = new EmployeeDAO();
			id = emDao.checkLogin(username, password);
			
			if(id == 0) {
				String error = "Invalid username or password";
				request.setAttribute("error", error);
				RequestDispatcher dispatcher = request.getRequestDispatcher("gui.jsp");
				dispatcher.include(request, response);
				
			}
			else {
				user = emDao.getAEmployee(id);
				HttpSession session = request.getSession();
				session.setAttribute("person", user);
				session.setMaxInactiveInterval(15*60);
				response.sendRedirect("gui.jsp");
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
